package com.ldg.crm.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ldg.crm.dao.UserDao;
import com.ldg.crm.entity.UserEntity;
import com.ldg.crm.entity.UserEntityExample;
import com.ldg.crm.entity.UserEntityExample.Criteria;
import com.ldg.crm.entity.UserSecurityEntity;
import com.ldg.crm.service.UserService;

@Service
public class UserServiceImp implements UserService,UserDetailsService {

	@Autowired
	UserDao userDao;

	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
		UserSecurityEntity userSecurity = null;
		System.out.println("***************************************" + userName);

		// 通过账号查询用户信息
		UserEntityExample example = new UserEntityExample();
		 Criteria criteria = example.createCriteria();
		 criteria.andUserNameEqualTo("ldg");
		 System.out.println(userDao);
		List<UserEntity> users = userDao.selectByExample(example);

		// 如果有用户信息返回则构建UserSecurityEntity对像
		if (users.size( ) > 0) {
			System.out.println( users.get(0) );
			userSecurity = new UserSecurityEntity();
			userSecurity.setUserName(userName);
			userSecurity.setUserPwd(users.get(0).getUserPwd());

			// 先设置假的权限
			List<GrantedAuthority> authorities = new ArrayList<>();
			
			// 传入角色
			authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
			userSecurity.setAuthorities(authorities);

		}

		return userSecurity;
	}

//	private Collection<SimpleGrantedAuthority> getAuthority(List<Role> roles) {
//	        ArrayList<SimpleGrantedAuthority> list = new ArrayList<>();
//	        for (Role role : roles) {
//	            list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
//	        }
//	        return list;
//	    }

}
